﻿using System;

namespace JXT.PrimaryKey.Batman.Core.Security
{
    /// <summary>
    /// 用户登录Membeship基类
    /// </summary>
    public abstract class MembershipBase : IMembership
    {
        private Authority[] _authorities;

        public Authority[] Authorities
        {
            get {
                if (_authorities != null) return _authorities;
                _authorities = Session.Authorities;
                return _authorities;
            }
        }

        private SecurityCookie _cookie;
        public SecurityCookie Cookie
        {
            get
            {
                if (_cookie != null) return _cookie;
                _cookie = LoadCookie();
                return _cookie;
            }
            protected set
            {
                _cookie = value;
            }
        }

        private SessionUser _session;
        public SessionUser Session
        {
            get {
                if (_session != null) return _session;
                _session = LoadSession();
                return _session;
            }
            protected set
            {
                _session = value;
            }
        }

        public bool IsLogin
        {
            get { return Cookie != null && Cookie.Id > 0; }
        }

        public DateTime? Expires { get; protected set; }

        public abstract bool LoginByName(string name, string password, DateTime? expired = null);

        public abstract bool LoginByMail(string mail, string password, DateTime? expired = null);

        public void Logout()
        {
            if (IsLogin)
            {
                RemoveCookie();
                RemoveSession();
            }
        }

        public void Reload()
        {
            if (IsLogin)
            {
                int id = Cookie.Id;
                RemoveCookie();
                RemoveSession();
                _cookie = CreateCookie(id);
                WriteCookie(_cookie, Expires);
                _session = null;
            }
        }

        protected abstract SecurityCookie LoadCookie();

        protected abstract void WriteCookie(SecurityCookie cookie, DateTime? time);

        protected abstract void RemoveCookie();

        protected abstract void RemoveSession();

        protected abstract SessionUser LoadSession();

        protected abstract void WriteSession(SessionUser session);

        protected abstract SecurityCookie CreateCookie(int userId);

        protected abstract SessionUser CreateSessionUser(int userId);
    }
}
